import os


def wordSearch(base):
    os.system("clear")

    def showMethod():
        print("a.列出所有单词")
        print("b.列出所有单词表")
        print("c.列出所有单词组")
        print("d.返回上一级")

    def showAllTables():
            allTables = base.selectAllTable()
            allTables.remove(('sqlite_sequence',))
            if not len(allTables):
                print("警告：没有单词表，请先添加")
                return False
            print("提示：以下为所有的单词表")
            for i in allTables:
                print("{}.{}".format(str(allTables.index(i) + 1), i[0]))
            return allTables

    showMethod()
    while True:
        ipt = input("请输入序号：")
        if ipt == 'exit' or ipt == 'd':
            break

        elif ipt == 'a':
            allTables = showAllTables()
            if (not allTables):
                continue
            iptTable = input("请输入单词所在的单词表：")
            if iptTable == 'exit':
                continue

            try:
                base.cur.execute('select * from {}'.format(allTables[int(iptTable) - 1][0]))
                searchWords = base.cur.fetchall()
            except Exception as e:
                # print(e)
                print("错误：此操作出错，请重试")
            else:
                os.system("clear")
                if len(searchWords) == 0:
                    print("警告：单词表中没有单词，请先添加")
                print("提示：以下为'{}'中的单词".format(allTables[int(iptTable) - 1][0]))
                print("(id, english, chinese, group)")
                for i in searchWords:
                    print(i)
                input("按任意键继续...")
                os.system("clear")
                showMethod()


        elif ipt == 'b':
            allTables = showAllTables()
            input("按任意键继续...")
            os.system("clear")
            showMethod()

        elif ipt == 'c':
            allTables = showAllTables()
            if (not allTables):
                continue
            iptTable = input("请输入单词所在的单词表：")
            if iptTable == 'exit':
                continue
            try:
                base.cur.execute('select "group" from {}'.format(allTables[int(iptTable) - 1][0]))
                searchWords = base.cur.fetchall()
            except Exception as e:
                print(e)
                print("错误：此操作出错，请重试")
            else:
                os.system("clear")
                searchWords = list(set(searchWords))
                if len(searchWords) == 0:
                    print("警告：单词表中没有单词组，请先添加")
                    continue
                print("提示：以下为'{}'中的单词组".format(allTables[int(iptTable) - 1][0]))
                for i in searchWords:
                    print(i[0])
                input("按任意键继续...")
                os.system("clear")
                showMethod()

        else:
            print("错误：没有此方法")